package com.goods.management.jms;

import com.goods.management.entity.Moduleinfo;
import com.goods.management.repository.ModuleInfoRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;

import javax.jms.*;
import java.util.Date;
import java.util.List;

@Service
public class Producer {
	private static Logger logger = LoggerFactory.getLogger(Producer.class);

	@Autowired // 也可以注入JmsTemplate，JmsMessagingTemplate对JmsTemplate进行了封装
	private JmsMessagingTemplate jmsMessagingTemplate;

	@Autowired
	ModuleInfoRepository moduleInfoRepository;


	// 发送消息，destination是发送到的队列，message是待发送的消息
	public void sendMessage(Destination destination, final String message) {
		jmsMessagingTemplate.convertAndSend(destination, message);
		/*logger.info("发送消息{}", message);*/
	}


	@JmsListener(destination = "modulesInfo.queue", containerFactory = "myJmsContainerFactory")
	public void consumerMessage(String text) {
		System.out.println("从moduleInfoDTO队列收到的回复报文为:" + text);
		String[] moduleInfo = text.split(",");
		String modulePort = moduleInfo[0].split("-")[1];
		Moduleinfo moduleinfo = new Moduleinfo(moduleInfo[0], moduleInfo[1], modulePort, Integer.parseInt(moduleInfo[2]), moduleInfo[3], moduleInfo[4], moduleInfo[5], Boolean.parseBoolean(moduleInfo[6]), new Date());
		List<Moduleinfo> moduleinfos = moduleInfoRepository.findModuleinfosByModuleIpAndModuleName(moduleInfo[1], moduleInfo[0]);
		if (moduleinfos.size() != 0) {
			Moduleinfo moduleinfoTemp = moduleinfos.get(0);
			moduleinfoTemp.setModuleLatency(moduleinfo.getModuleLatency());
			moduleinfoTemp.setOccupiedRateOfBandwidth(moduleinfo.getOccupiedRateOfBandwidth());
			moduleinfoTemp.setOccupiedRateOfCpu(moduleinfo.getOccupiedRateOfCpu());
			moduleinfoTemp.setOccupiedRateOfMemory(moduleinfo.getOccupiedRateOfMemory());
			moduleinfoTemp.setModuleCondition(moduleinfo.getModuleCondition());
			moduleinfoTemp.setUpdateTime(moduleinfo.getUpdateTime());
			moduleInfoRepository.save(moduleinfoTemp);
		} else {
			moduleInfoRepository.save(moduleinfo);
		}

	}


}
